﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightAnimation
{
    public abstract class TransformAnimation<T> : AnimationBase where T : Transform, new()
    {
        protected TransformAnimation(FrameworkElement element, TimeSpan duration)

            : base(element, duration)
        {
        }
        protected int PrepareElement(FrameworkElement element)
        {
            TransformGroup transformGroup = null;
            if (element == null)
                throw new ArgumentNullException("element");

            //if the element does not have a transform group create a new group
            if (element.RenderTransform == null)
            {
                transformGroup = new TransformGroup();
                transformGroup.Children.Add(new T());
                element.RenderTransform = transformGroup;
                return 0;
            }
            //if the element already have a transform group add a transform of type T
            if (element.RenderTransform is TransformGroup)
            {
                transformGroup = new TransformGroup();

                transformGroup.Children.Add(new T());
                element.RenderTransform = transformGroup;

                transformGroup = (TransformGroup)element.RenderTransform;
                transformGroup.Children.Add(new T());

                return transformGroup.Children.Count - 1;
            }
            if (!(element.RenderTransform is TransformGroup))
            {
                transformGroup = new TransformGroup();
                transformGroup.Children.Add(new T());
                element.RenderTransform = transformGroup;
                return 0;
            }
            return -1;
        }
        private bool HasTransform(FrameworkElement element)
        {
            foreach (Transform transform in ((TransformGroup)element.RenderTransform).Children)
            {
                if (transform is T)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
